/**
 * Date：2017.05.14 星期日 晚上
 * Function：留言控制操作
 * E-mail：woaitianwen@qq.com
 * Author：zhouyulong
 */

'use strict';
var jwt = require('jsonwebtoken');
var mongoose = require('mongoose'),
    Comment = mongoose.model('Comments');

//留言CRUD首页
exports.comment_view = function(req, res) {
    
    res.render('contact_view', {title: '留言CRUD页面'});
}
//获取全部留言
exports.all_comments = function(req, res) {
    Comment.find({}, function(err, comment) {
        if (err) {
           res.json({success: false, status: 1, msg: '无法读取！'}); 
        }
        res.json(comment);
    })
}

//创建留言
exports.create_comment = function(req, res) {
    var new_comment = new Comment({
        username: req.body.username,
        weixin: req.body.weixin,
        email: req.body.email,
        comments: req.body.comments
    });
    new_comment.save(function(err, comment) {
        if (err) {
            return res.json({success: false, status: 1, msg: '提交失败！'});
        }
        res.json({success: true, status: 0, msg: '提交成功！'});
    });
}
//获取留言ID
exports.read_comment = function(req, res) {
     Comment.findById(req.params.commentId, function(err, comment) {
         if (err) {
             return res.json({success: false, status: 1, msg: '找不到用户ID！'});
         }
         res.json(comment);
     });
}
//更新留言
exports.update_comment = function(req, res) {
    Comment.findByIdAndUpdate(req.params.commentId, req.body, {new: true}, function(err, comment) {
        if (err) {
            return res.json({success: false, status: 1, msg: '更新失败！'});
        }
        return res.json({success: true, status: 0, msg: '更新成功！'});
    })
}

//删除一篇留言
exports.delete_comment = function(req, res) {
    Comment.remove({
        _id: req.params.commentId
    }, function(err, comment) {
        if (err) {
            return res.json({success: false, status: 1, msg: '删除失败！'});
        }
        return res.json({success: true, status: 0, msg: '删除成功！'});
    })
}
//实现分页查询和条件搜索

/*exports.search_comment = function(req, res) {
    var count = 0;
    var page = req.body.page;
    var rows = req.body.rows;
     
    var username = req.body.username;
    console.log(username);
    console.log("page:"+page+",rows:"+rows);
     
    var query = Comment.find({});
    query.skip((page - 1)*rows);
    query.limit(rows);
    if(username){
        query.where('username',username);
    }
    //计算分页数据
    query.exec(function(err,rs){
        if(err){
            res.send(err);
        }else{
            //计算数据总数
            Comment.find(function(err,result){
                jsonArray={rows:rs,total:result.length};
                res.json(jsonArray);
            });
             
        }
    });

}*/



